package me.huanmeng.heater.command.manager;

import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import me.huanmeng.heater.command.Command;
import me.huanmeng.heater.command.defaults.ClearChatCommand;
import me.huanmeng.heater.command.defaults.TestCommand;
import me.huanmeng.heater.plugin.Plugin;
import me.huanmeng.heater.sender.Channel;
import me.huanmeng.heater.sender.CommandSender;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 2021/9/26<br>
 * Heater<br>
 * 指令管理器
 *
 * @author huanmeng_qwq
 */
public final class CommandManager {
    private final Multimap<Plugin, Command> pluginCommands = HashMultimap.create();
    private final ConcurrentHashMap<String, Command> commands = new ConcurrentHashMap<>();

    public CommandManager() {
        defReg(new TestCommand());
        defReg(new ClearChatCommand());
    }

    void defReg(Command command) {
        commands.put(command.getName(), command);
        if (command.getAliases() != null) {
            for (String alias : command.getAliases()) {
                commands.put(alias, command);
            }
        }
    }

    public void register(@NotNull Plugin plugin, Command command) {
        pluginCommands.put(plugin, command);
        commands.put(command.getName(), command);
        if (command.getAliases() != null) {
            for (String alias : command.getAliases()) {
                commands.put(alias, command);
            }
        }
    }

    private Command getCommand(String cmd) {
        final Map.Entry<String, Command> entry = commands.entrySet().stream().filter(e -> e.getKey().equalsIgnoreCase(cmd)).findFirst().orElse(null);
        return entry == null ? null : entry.getValue();
    }

    public void executeCommand(@NotNull CommandSender sender, @Nullable Channel channel, @NotNull String line) {
        if (!line.startsWith("/") && !line.startsWith(".") && !line.startsWith("。")) {
            return;
        }
        String label;
        if (line.contains(" ")) {
            label = line.split(" ")[0].substring(1);
        } else {
            label = line.substring(1);
        }
        final Command command = getCommand(label);
        if (command == null) {
            return;
        }
        final String[] s = line.split(" ", -1);
        String[] args = Arrays.copyOfRange(s, 1, s.length);
        command.execute(sender, channel, label, Arrays.asList(args));
    }
}
